<!--vue模板-->
<template>
  <div class="container">
    <el-dialog
      :model-value="visible"
      title="添加字典"
      width="500"
      :close-on-click-modal="false"
      draggable="true"
      @close="close"
    >
      <el-form ref="addForm" :model="dict" :rules="rules">
        <el-form-item label="编码" prop="code">
          <el-input v-model="dict.code" placeholder="请输入编码" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="dict.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="dict.sorts" />
        </el-form-item>
      </el-form>

      <div style="text-align: right">
        <el-button type="primary" @click="saveDict">保存</el-button>
        <el-button type="info" @click="close">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<!--vue 组件选项定义-->
<script setup>
import { ref } from "vue";
import { saveDic, updateDic } from "@/api/product/product.js";
import { ElMessage } from "element-plus";
const addForm = ref();
//定义属性
const props = defineProps({
  visible: {
    type: Boolean,
    default: false //默认值
  }
});

//声明事件   需要父组件监听
const emits = defineEmits(["close", "refreshData"]);

//表单数据
const dict = ref({
  code: "",
  name: "",
  pid: 0,
  sorts: 0
});

//验证规则
const rules = {
  code: [{ required: true, message: "请输入编码", trigger: "blur" }],
  name: [{ required: true, message: "请输入名称", trigger: "blur" }]
};

//关闭对话框回调
function close() {
  //触发关闭事件 通知父组件
  emits("close");
}

function init(pid, row) {
  if (row) {
    //编辑
    dict.value = row;
  } else {
    //新增
    dict.value = {
      code: "",
      name: "",
      pid: pid,
      sorts: 0
    };
  }
}

//保存
async function saveDict() {
  let valid = await addForm.value.validate(() => {});
  if (!valid) return;
  let res;
  if (dict.value.id) {
    //说明修改
    res = await updateDic(dict.value);
  } else {
    //说明 新增字典
    res = await saveDic(dict.value);
  }

  if (res.code == 200) {
    ElMessage({
      message: "保存成功",
      type: "success"
    });
    //通知父组件 刷新数据
    emits("refreshData");
    close();
  }
}

//暴露方法 供父组件调用
defineExpose({ init });
</script>

<!--vue样式 scoped当前样式只适用于当前组件-->
<style scoped>
.container {
  padding: 0;
}
</style>
